package com.ktjy.unti;

import com.ktjy.pojo.SysRoleRight;
import com.ktjy.pojo.vo.SysUserVo;
import com.ktjy.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义域
 */
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    SysUserService userService;

    /**
     * 授权
     *
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUserVo sysUserVo = (SysUserVo) principals.getPrimaryPrincipal();
        //获取用户拥有的权限
      List<SysRoleRight> rightList =  userService.getListSysRight(sysUserVo.getUsrRoleId());
      SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
      List<String> list = new ArrayList<>();
        for (SysRoleRight sysRoleRight : rightList) {
            list.add(sysRoleRight.getRfRightCode());
        }
        simpleAuthorizationInfo.addStringPermissions(list);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     *
     * @param token the authentication token containing the user's principal and credentials.
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        SysUserVo sysUserVo = userService.loginToken(userName);
        if (sysUserVo == null) {
            throw new UnknownAccountException();
        }
        if (sysUserVo.getUsrFlag() == 0) {
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                sysUserVo,
                sysUserVo.getUsrPassword(),
                ByteSource.Util.bytes("czkt"),
                getName());
        return info;
    }
}
